import 'package:common/base/base_present.dart';
import 'package:common/constant/constant.dart';
import 'package:common/utils/log_util.dart';
import 'package:dio/dio.dart';

import '../../constant/http_constant.dart';
import '../../network/code_msg_model.dart';
import '../../network/dio_manager.dart';
import 'common_api_path.dart';

//文件上传
class UploadPresent extends BasePresent {
  UploadPresent(super.businessResponse);

  //上传单个文件
  Future<void> uploadFileByPath(String filePath, ProgressCallback? onSendProgress) async {
    try {
      final formData = FormData.fromMap({
        'file': MultipartFile.fromFileSync(filePath),
      });
      Map<String, String> queryParameters = {
        'project': Constant.projectName,
        'folderName': Constant.folderName
      };
      DioManager.external(HttpConstant.baseUrl).httpPostByPath(
          CommonApiPath.uploadFilePath, formData, businessResponse,
          queryParameters: queryParameters, onSendProgress: onSendProgress);
    } on Exception catch (exception) {
      LogUtil.stdPrint(exception);
      CodeMsgModel codeMsgModel = CodeMsgModel();
      codeMsgModel.code = Constant.fail.toString();
      codeMsgModel.msg = exception.toString();
      businessResponse.onFail(codeMsgModel);
    }
  }

  //上传多个文件
  Future<void> uploadFilesByPath(List<String> filePaths, ProgressCallback? onSendProgress) async {
    try {
      final formData = FormData();
      final files = <MapEntry<String, MultipartFile>>[];
      for (String filePath in filePaths) {
        files.add(MapEntry(
          'multipartFiles',
          MultipartFile.fromFileSync(filePath),
        ));
      }
      formData.files.addAll(files);

      Map<String, String> queryParameters = {
        'project': Constant.projectName,
        'folderName': Constant.folderName
      };
      DioManager.external(HttpConstant.baseUrl).httpPostByPath(
          CommonApiPath.uploadFilesPath, formData, businessResponse,
          queryParameters: queryParameters, onSendProgress: onSendProgress);
    } on Exception catch (exception) {
      LogUtil.stdPrint(exception);
      CodeMsgModel codeMsgModel = CodeMsgModel();
      codeMsgModel.code = Constant.fail.toString();
      codeMsgModel.msg = exception.toString();
      businessResponse.onFail(codeMsgModel);
    }
  }
}
